package com.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.domain.common.AppLogger;
import com.domain.common.Comments;
import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.dao.*;
import com.domain.pojo.*;
import com.domain.service.BillService;
import com.domain.service.PublishService;
import com.domain.service.PushMessageService;
import com.domain.utils.ArithmeticUtil;
import com.domain.utils.HongBaoAlgorithm;
import com.domain.utils.UUIDUtils;
import com.domain.utils.alipay.AlipayUtil;
import com.domain.utils.jiguang.Jdpush;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class PublishServiceImpl implements PublishService {

    /**
     * 日志
     */
    private static Logger logger = AppLogger.getLogger(PublishServiceImpl.class.getSimpleName(), Level.INFO.toString(), true);
    @Autowired
    private PublishMapper publishMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private PublishAcceptanceMapper publishAcceptanceMapper;


    @Autowired
    private UsersFillterPublishUsersMapper usersFillterPublishUsersMapper;


    @Autowired
    private BillService billService;


    @Autowired
    private UsersHelpMapper usersHelpMapper;

    @Autowired
    private PushMessageService pushMessageService;

    /**
     * 发布求助
     *
     * @param userId
     * @param typeId
     * @param publishTitle
     * @param publishContent
     * @param filterUserId
     * @param longitude
     * @param latitude
     * @param itIsPaid
     * @param cityName
     * @param images
     * @param money
     * @param
     * @return
     */
    @Override
    public Result savePublish(String userId, String typeId, String publishTitle, String publishContent, String filterUserId, String longitude, String latitude, String itIsPaid, String cityName, String images, String money) {
        Publish p = new Publish();
        String publishId = UUIDUtils.getRandomUUID();
        p.setId(publishId);
        p.setTitle(publishTitle);
        p.setCityName(cityName);
        p.setContent(publishContent);
        p.setCreatTime(new Date());
        p.setImages(images);
        p.setItIsPaid(new Integer(itIsPaid));//是否有偿
        p.setLatitude(latitude);
        p.setLongitude(longitude);
        p.setSpareOne(typeId);
        p.setSpareTwo(new BigDecimal(money));
        p.setType(Comments.PUBLISH_TYPE_HAVE_IN_HAND);
        p.setState(Comments.STATE_NORMAL);
        p.setUserId(userId);
        publishMapper.insertSelective(p);
        //保存该发布的过滤的好友
        //filterUserId，得到json数组
        JSONArray array = JSON.parseArray(filterUserId);
        for (int i = 0; i < array.size(); i++) {
            //添加发布过滤的好友id
            JSONObject o = array.getJSONObject(i);
            UsersFillterPublishUsers ufpu = new UsersFillterPublishUsers();
            ufpu.setId(UUIDUtils.getRandomUUID());
            ufpu.setFillterUserId(o.getString("userId"));
            ufpu.setPublishId(publishId);
            ufpu.setCreatTime(new Date());
            ufpu.setUserId(userId);
            usersFillterPublishUsersMapper.insertSelective(ufpu);
        }
        return Result.success("发布成功", "");
    }

    /**
     * 我的发布列表
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result getUsersPublish(String userId, String pageNum, String pageSize) {
        PageHelper.startPage(new Integer(pageNum), new Integer(20));
        List<Map<String, Object>> publishMaps = publishMapper.selectByUserIdMaps(userId);
        Map<String, Object> map = new HashMap<>();
        if (publishMaps.size() == 0) {
            Map<String, Object> maps = new HashMap<>();
            maps.put("pId", "");
            maps.put("pTitle", "");
            maps.put("pIsItPaid", "");
            maps.put("pcreatTime", "");
            maps.put("redPackge", "");
            maps.put("icons", "");
            maps.put("forwarfCount", "");
            publishMaps.add(maps);
        }
        //获取发布得评论条数
        List<Comment> comments = new ArrayList<>();
        //获取帮忙条数
        List<PublishAcceptance> publishAcceptances = new ArrayList<>();
        for (Map<String, Object> mapsa : publishMaps) {
            comments = commentMapper.selectBypublishId(mapsa.get("pId").toString());
            publishAcceptances = publishAcceptanceMapper.selectByPublish(mapsa.get("pId").toString());
        }
        PageInfo pageResult = new PageInfo(publishMaps);
        map.put("commentSize", comments.size());
        map.put("publishAcceptancesSize", publishAcceptances.size());
        map.put("list", pageResult.getList());
        return Result.success("操作成功", map);
    }

    /**
     * 获取用户发布详情
     *
     * @param userId    用户id
     * @param publishId 发布id
     * @return
     */
    @Override
    public Result getUserPublishDetail(String userId, String publishId) {
        Map<String, Object> maps = new HashMap<>();
        //发布信息
        Publish publish = publishMapper.selectByPrimaryKey(publishId);
        //用户id跟发布者id相同（自己看自己的发布）
        if (userId.equals(publish.getUserId())) {
            return Result.publicResult(401, "自己看自己的发布");
        }
        //发布者信息
        Users users = usersMapper.selectByPrimaryKey(publish.getUserId());
        //评论数量
        List<Comment> size = commentMapper.selectBypublishId(publishId);
        maps.put("userInfo", users);
        maps.put("publishInfo", publish);
        maps.put("commentsSize", size.size());
        return Result.success("操作成功", maps);
    }


    /**
     * 完成帮忙
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Result completePublish(String userId, String publishId) {
        //判断红包钱数和帮转人数是否成比例（每人最低分配一分钱）
        //获取去重的帮转人id
        List<UsersHelp> usersHelps = usersHelpMapper.selectByDistinct(publishId);
        //发布的信息
        Publish pu = publishMapper.selectByPrimaryKey(publishId);
        //如果发布的信息红包大于零  发帮转红包
        logger.info("发红包开始***************************************");
        if (pu.getSpareTwo().doubleValue() > 0 && usersHelps.size() < 0) {
            //没有人帮忙转发  余额退回至发布人
            Users user = usersMapper.selectByPrimaryKey(pu.getUserId());
            String pushId = UUIDUtils.getRandomUUID();
            //推送至发布人余额退回信息
            int results = Jdpush.sendToAliasList(user.getId(), "您的红包余额已经退回到您的账户", pushId, Const.red_pacakge_return, "红包余额退回");
            if (results == 1) {
                //推送成功添加推送记录
                pushMessageService.addSystemMessage(user.getId(), "", "您的红包余额已经退回到您的账户", "红包余额退回", publishId, Const.red_pacakge_return, pushId);
                //添加账单信息
                billService.addBill(user.getId(), "红包余额退款", Comments.SERZERBAL_PUT, pu.getSpareTwo().toString(), Const.RED_PACKAGE_ICONS);
            }
        } else {
            //获取每个人发红包的钱数
            List<BigDecimal> money = HongBaoAlgorithm.math(pu.getSpareTwo(), usersHelps.size());
            for (BigDecimal b : money) {
                if (b.doubleValue() > 0) {
                    //发红包推送给帮转人
                    for (UsersHelp h : usersHelps) {
                        //推送红包用户信息
                        Users users = usersMapper.selectByPrimaryKey(pu.getUserId());
                        String pushId = UUIDUtils.getRandomUUID();
                        int result = Jdpush.sendToAliasList(h.getHelpId(), "" + users.getName() + "帮忙信息已经完成,感谢您得帮转", pushId, Const.getRed_package, "红包通知");
                        if (result == 1) {
                            //推送成功添加推送记录
                            pushMessageService.addAcknowledgeMessage(h.getHelpId(), pu.getUserId(), "" + users.getName() + "帮忙信息已经完成,感谢您得帮转", "红包通知", b.toString(), Const.getRed_package, pushId);
                        }
                    }
                }
            }
        }
        //更新状态
        //todo
        return null;
    }

    /**
     * 帮转红包支付
     *
     * @param userId       用户id
     * @param body
     * @param subject
     * @param total_amount
     * @return
     */
    @Override
    public Result helpRedPacakgePay(String userId, String body, String subject, String total_amount) throws AlipayApiException {
        AlipayTradeAppPayResponse response = AlipayUtil.creatAlipayOrder(body, subject, total_amount);
        if (response.isSuccess()) {
            //支付成功添加账单信息
            billService.addBill(userId, "帮转红包付款", Comments.SERZERBAL_OUT, total_amount, Const.RED_PACKAGE_ICONS);
        }
        return Result.success(response);
    }

    /**
     * 发布补加红包
     *
     * @param userId
     * @param money
     * @param publishId
     * @param body
     * @param subject
     * @return
     */
    @Override
    public Result helpRedPacakgeSupplement(String userId, String money, String publishId, String body, String subject) throws AlipayApiException {
        AlipayTradeAppPayResponse response = AlipayUtil.creatAlipayOrder(body, subject, money);
        if (response.isSuccess()) {
            //支付成功添加发布补加的钱数
            Publish pu = publishMapper.selectByPrimaryKey(publishId);
            Publish p = new Publish();
            p.setId(publishId);
            p.setUpdateTime(new Date());
            BigDecimal moneys = ArithmeticUtil.add(pu.getSpareTwo().toString(), money.toString());
            p.setSpareTwo(moneys);
            publishMapper.updateByPrimaryKeySelective(p);
            //添加账单
            billService.addBill(userId, "帮转红包付款", Comments.SERZERBAL_OUT, money, Const.RED_PACKAGE_ICONS);
        }
        return Result.success(response);
    }

    /**
     * 完成帮忙判断
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Result judgeCompletePublish(String userId, String publishId) {
        //获取去重的帮转人id
        List<UsersHelp> usersHelps = usersHelpMapper.selectByDistinct(publishId);
        //发布的信息
        Publish pu = publishMapper.selectByPrimaryKey(publishId);
        //判断发布的红包是否大于零
        if (pu.getSpareTwo().doubleValue() > 0 && usersHelps.size() > 0) {
            //红包不足缺的钱数（帮转人*0.01-发布红包的钱数）
            double moneys = ArithmeticUtil.mul(usersHelps.size(), 0.01);
            double subMoney = ArithmeticUtil.sub(moneys, pu.getSpareTwo().doubleValue());
            //获取每个人发红包的钱数
            List<BigDecimal> money = HongBaoAlgorithm.math(pu.getSpareTwo(), usersHelps.size());
            if (money == null) {
                return Result.publicResult(401, "红包余额不足，请补发红包", subMoney);
            } else {
                //完成帮忙
                completePublish(userId, publishId);
            }
        }
        return Result.success();
    }

}

